from fastapi import HTTPException, status
from datetime import timedelta
from ..dependencies import success, router, app, depens, User
from ..models.adv import Adv
from ..models.base import Item
from ..models.user import Favorite
from ..utils.identity import login, create_access_token, hash_password
from ..config import secret
from pydantic import BaseModel, Field

@router.get("/home", dependencies=depens(False))
async def home():
    return success({
        'swipers': [row for row in Adv.select().where(Adv.block_id == 1).order_by(Adv.id.desc()).paginate(1, 10).dicts()],
        'list': [row for row in Item.select().order_by(Item.id.desc()).paginate(0, 10).dicts()], 
        'total': Item.select().count()
    })

### 登录
class LoginForm(BaseModel):
    mobile: str = Field(title="用户名", default='', max_length=20)
    password: str = Field(title="米啊", default='', max_length=11)

@router.post("/login")
async def index(post: LoginForm):
    user = login(post.mobile, post.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password"
        )
    access_token_expires = timedelta(minutes=secret['expire'])
    access_token = create_access_token(
        data={'id': user['id'], 'mobile': user['mobile']}, expires_delta=access_token_expires
    )
    app.state.user = user
    return success({
        'access_token': access_token,
        **user
    })

### 注册
class SignupForm(BaseModel):
    mobile: str = Field(title="手机号", default='', max_length=20)
    sms: str = Field(title="短信验证码", default='', max_length=6)
    password: str = Field(title="手密码", default='', max_length=16)
    repeat: int = Field(title="确认密码", default='', max_length=16)
### 注册 ###
@router.post("/signup")
async def index(post: SignupForm):
    model = User.get(User.mobile==post.mobile)
    if not model is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Mobile Number is exits"
        )
    model = User.create(mobile=post.mobile, password=hash_password(post.password))
    access_token_expires = timedelta(minutes=secret['expire'])
    access_token = create_access_token(
        data={'id': model['id'], 'mobile': model['mobile']}, expires_delta=access_token_expires
    )
    app.state.user = model
    return success({
        'access_token': access_token,
        **model.__data__
    })
### 忘记密码 ###
@router.post("/forget")
async def index(post: SignupForm):
    model = User.get(User.mobile==post.mobile)
    if model is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Mobile Number is not exits"
        )
    access_token_expires = timedelta(minutes=secret['expire'])
    access_token = create_access_token(
        data={'id': model['id'], 'mobile': model['mobile']}, expires_delta=access_token_expires
    )
    app.state.user = model
    return success({
        'access_token': access_token,
        **model.__data__
    })
